import type { KeepAlive } from '#/router';
import store from '@/store';
import type { Router, RouteLocationNormalized } from 'vue-router';

export default function routerGuard(router: Router) {
  router.beforeEach(async (to, from, next) => {
    // 设置路由缓存
    await setKeepAlive(to, from);
    next();
  });
}

/**
 *
 * @param to {RouteLocationNormalized}
 * @param from  {RouteLocationNormalized}
 */
async function setKeepAlive(to: RouteLocationNormalized, from: RouteLocationNormalized) {
  const fromKeepAlive: KeepAlive = (from.meta?.keepAlive as string[]) || [];
  const toKeepAlive: KeepAlive = (to.meta.keepAlive as string[]) || [];

  // if (typeof fromKeepAlive === 'boolean' && fromKeepAlive) {
  //   await store.dispatch('app/addKeepAlive', from.name);
  // }
  // if (typeof fromKeepAlive === 'boolean' && !fromKeepAlive) {
  //   await store.dispatch('app/deleteKeepAlive', to.name);
  // }

  // if (fromKeepAlive.includes(to.name as string)) {
  //   await store.dispatch('app/addKeepAlive', from.name);
  // } else {
  //   await store.dispatch('app/deleteKeepAlive', from.name);
  // }

  // if (!toKeepAlive.includes(from.name as string)) {
  //   await store.dispatch('app/deleteKeepAlive', to.name);
  // }
}
